<?php
class SysconfigModel extends CommonModel {
	public function __construct(){
		parent::__construct();
	}
	function query_sysconfig($group){
		$data = array();
		foreach($group as $kk => $v ){
			$list_data = M("Sysconfig")->where("groupid = {$kk}")->order("disorder asc")->select();

			if($list_data){
				foreach($list_data as $k1=>$v1){
			
					$text = '' ;
					$v1['varname'] = $v1['varname'].'[]';
					if(in_array($v1['type'],array('number','string'))){
						$text = "<input type='text' class=\"common-text\" name='{$v1['varname']}' value='{$v1['value']}'>";
					}elseif($v1['type'] == 'boolean'){
						if($v1['value'] == 'Y'){
							$text = "是<input type='radio' name='{$v1['varname']}' value='Y' checked='checked'>否<input type='radio' name='{$v1['varname']}' value='N'>";
						}else{
							$text = "是<input type='radio' name='{$v1['varname']}' value='Y'>否<input type='radio' name='{$v1['varname']}' value='N' checked='checked'>";
						}
			
					}elseif($v1['type'] == 'textarea'){
						$text = "<textarea style='border:solid 1px #A7B5BC ;width:345px ; height:90px' class='dfinput' name='{$v1['varname']}' style='width:360px'>{$v1['value']}</textarea>";
					}elseif($v1['type'] == 'file'){
						$rand = $kk."_".rand();
						$text = "<img src=".C('upload_domain')."/Sysconfig/{$v1['value']} width='80' height='80'>";
						$text .= "<input type='text'readonly  id=\"value_pic_{$rand}\"  class=\"common-text\" name='{$v1['varname']}' value='{$v1['value']}'><span id='pic_{$rand}'  onclick=\"ajax_upload_pic('pic_{$rand}')\" style=\"cursor:pointer\">上传</span>";
						//$text.="<input type=\"text\" name=\"file_pic_{$rand}\" style=\"position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;\">";
					}
					$text.="&nbsp;排序：<input type='text' class='dfinput' style='border:solid 1px #A7B5BC ;width:50px ; ' name='{$v1['varname']}__my57sy_{$v1['disorder']}[]' value='{$v1['disorder']}'>";
					$del_url = U("sysconfig/del" , array('varname'=>$v1['varname'] , 'gid'=>$kk ) ) ; 
					$text.="&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"tablelink\"  href=\"javascript:void(0)\" onclick=\"del_var('{$del_url}' , '{$v1['varname']}' )\">删除</a>";
					$list_data[$k1]['text'] = $text ;
				}
			}
			$data[$kk] = $list_data ;
			
		}
		return $data ;
	}
	//根据varname查询是否存在
	public function query_isexists_by_varname($varname){
		$info = M("Sysconfig")->where("varname = '{$varname}'")->find();
		if($info){
			return true ;
		}
		return false ;

	}
	//插入系统环境变量
	public function insert_sysconfig($data){
		if(empty($data['varname'])){
			return array('status' => 0 , 'message'=>'varname is empty');
		}
		if(utf8_str($data['varname']) != 1 ){
			return array('status' => 0 , 'message'=>'变量名称必须是英文');
		}
		if($data['type'] == 'file' ){
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 3145728 ;// 设置附件上传大小
			$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->savePath =  './Data/Upload/Sysconfig/';// 设置附件上传目录
			$upload->autoSub = true;//使用子目录保存上传文件
			$upload->subType = 'date';//使用日期模式创建子目录
			$upload->dateFormat = 'Ymd';//设置子目录日期格式
			if(!$upload->upload()) {// 上传错误提示错误信息
				return array('status' => 0 , 'message'=> $upload->getErrorMsg());
				
			}else{// 上传成功 获取上传文件信息
				$info =  $upload->getUploadFileInfo();
			}
			$data['value'] = $info[0]['savename'];
		}else{
			if($data['type'] == 'boolean' && !in_array($data['value'], array('N' , 'Y'))){
				return array('status' => 0 , 'message'=>'变量类型是boolean，值必须是 N或者Y');
					
			}
		}
	
		$exists = $this->query_isexists_by_varname($data['varname']);
		if($exists){
			return array('status' => 0 , 'message'=>'变量名称存在');
		}
		$res = M("Sysconfig")->add($data);
		$sql = M("Sysconfig")->getLastSql();
		if($res>=1){
			$this->make_sysconfig();
			return array('status' => 1 , 'message'=>'添加成功');
			write_action_log($sql,getModuleAction(),$this->username,get_client_ip(),1,"添加系统变量{$data['varname']}成功");
			return true ;
		}else{
			return array('status' => 0 , 'message'=>'网络繁忙请稍后');
			write_action_log($sql,getModuleAction(),$this->username,get_client_ip(),0,"添加系统变量{$data['varname']}失败");
			return false ;
		}
	}
	//修改数据
	public function update_data($data){

		if($data){
			foreach($data as $last_key=>$last_val){
				//$last_val = $this->db->escape_str($last_val);
				/* $last_val = daddslashes(html_escape(strip_tags($last_val)));
					$last_key = daddslashes(html_escape(strip_tags($last_key))); */
				$disorder = 0 ;
				$disorder = intval(isset($last_val[1])?$last_val[1]:0);
				$value = (isset($last_val[0]))?($last_val[0]):'';
				if(empty($value)){
					continue ;
				}
				M("Sysconfig")->where("varname = '{$last_key}' ")->save(
					array('value'=>$value , 'disorder'=>$disorder )		
				);
		
	
			}
	
			$this->make_sysconfig();
			write_action_log("sysconfig_update",getModuleAction(),$this->username,get_client_ip(),1,"修改系统变量成功");
			return true ;
		}else{
			write_action_log("sysconfig_update",getModuleAction(),$this->username,get_client_ip(),0,"修改系统变量失败");
			return false ;
		}
	
	}
	//删除
	//删除数据
	public function del_varname($varname){
		$num =  M("Sysconfig")->where("varname = '{$varname}' ")->delete();
		$sql = M("Sysconfig")->getLastSql();
		if($num){
			write_action_log($sql,getModuleAction(),$this->username,get_client_ip(),1,"删除环境变量{$varname}成功");
			$this->make_sysconfig();
			return true ;
		}
		write_action_log($sql,getModuleAction(),$this->username,get_client_ip(),0,"删除环境变量{$varname}失败");
		return false ;
	}
	//生成
	public function make_sysconfig(){
		$list_data = M("Sysconfig")->select();
		if(!is_writable(CONF_PATH."Admin")){
			exit("目录".CONF_PATH."Admin"."不可写");
		}
		
	
		$configfile = CONF_PATH."sysconfig.php";
		$time = date("Y-m-d H:i" , time());
		$fp = fopen($configfile,'w');
		flock($fp,3);
		fwrite($fp,"<"."?php\r\n");
		fwrite($fp,"/*系统的基本信息配置*/\r\n");
		fwrite($fp,"/*author wangjian*/\r\n");
		fwrite($fp,"/*time {$time}*/\r\n");
	
		$data = array() ;
		if($list_data){
			foreach($list_data as $j_key=>$j_val){
				$value =$j_val['value'];
				if($j_val['type'] == 'number'){
					$value = intval($j_val['value']);
				}elseif($j_val['type'] == 'file'){
					$value =C('upload_domain')."/Sysconfig/".$j_val['value'];
				}
				$data[$j_val['varname']] = $value ;
				//fwrite($fp,"\${$j_val['varname']} ='{$value}';\r\n");
			}
		}
		$string = "return  " ;
		$string.= var_export($data , true ) ;
	
		fwrite($fp,"$string;\r\n");
	}	
}
